package com.mxnet.chongjin.supoman.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.utils.EmailCheckUtils;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class RegistActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
    private Context mContext;
    private LinearLayout mLinearLayout;
    private TextView mTextView;
    private ImageView mImageView;
    private Button mButton, mBtnIndentCode;
    private EditText mEt1, mEt2, mEt3;
    private Boolean isCheck;
    private TimeCount mTimeCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = RegistActivity.this;
        mTimeCount = new TimeCount(60000, 1000);

        initView();
        initData();
    }

    public void initData() {
        isCheck = false;
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_regist);
        mLinearLayout.setOnClickListener(this);

        mTextView = findViewById(R.id.tv_regist_registration_agreement);
        mTextView.setOnClickListener(this);

        mImageView = findViewById(R.id.iv_regist_choose);
        mImageView.setOnClickListener(this);

        mButton = findViewById(R.id.btn_regist);
        mButton.setOnClickListener(this);

        mBtnIndentCode = findViewById(R.id.btn_regist_get_verification_code);
        mBtnIndentCode.setOnClickListener(this);

        mEt1 = findViewById(R.id.et_regist_email);
        mEt1.addTextChangedListener(this);

        mEt2 = findViewById(R.id.et_regist_verification_code);

        mEt3 = findViewById(R.id.et_regist_set_pwd);
    }

    @Override
    public void onClick(View v) {
        final Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.ll_regist:
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.btn_regist_get_verification_code:
                mEt1.setFocusable(false);
                mEt1.setFocusableInTouchMode(false);
                OkHttpUtils.get()
                        .url(Api.URL_HEADER + Api.EMAIL_CHECKCODE)
                        .addParams("userCode", new String(mEt1.getText().toString().getBytes()))
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                e.printStackTrace();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean isSuccess = jsonObject.optBoolean("success");
                                        if (isSuccess) {
                                            ToastUtils.showToast(mContext, getResources().getString(R.string.send_success));
                                        } else {
                                            ToastUtils.showToast(mContext, getResources().getString(R.string.send_failed));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                mTimeCount.start();
                break;
            case R.id.tv_regist_registration_agreement:
                intent.setClass(mContext, RegistrationAgreementActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.iv_regist_choose:
                if (!isCheck) {
                    isCheck = true;
                    mImageView.setImageResource(R.mipmap.regist_icon_check_check);
                    mButton.setBackground(getResources().getDrawable(R.drawable.btn_shape));
                    mButton.setClickable(true);
                } else {
                    isCheck = false;
                    mImageView.setImageResource(R.mipmap.regist_icon_check_default);
                    mButton.setBackground(getResources().getDrawable(R.drawable.btn_regist_shape));
                    mButton.setClickable(false);
                }
                break;
            case R.id.btn_regist:
                if (!TextUtils.isEmpty(mEt1.getText()) && !TextUtils.isEmpty(mEt2.getText()) && !TextUtils.isEmpty(mEt3.getText())) {
                    OkHttpUtils.get()
                            .url(Api.URL_HEADER + Api.CUSTOMER_RESGIST)
                            .addParams("userCode", mEt1.getText().toString())
                            .addParams("indentCode", mEt2.getText().toString())
                            .addParams("password", mEt3.getText().toString())
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {

                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    if (!TextUtils.isEmpty(response)) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            boolean isSuccess = jsonObject.optBoolean("success");
                                            if (isSuccess) {
                                                ToastUtils.showToast(mContext, getResources().getString(R.string.regist_success));
                                                JSONObject data = jsonObject.optJSONObject("data");
                                                intent.setClass(mContext, UserLoginActivity.class);
                                                mContext.startActivity(intent);
                                            } else {
                                                ToastUtils.showToast(mContext, getResources().getString(R.string.account_exist));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                } else {
                    ToastUtils.showToast(mContext, getResources().getString(R.string.regist_complete));
                }
                break;
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(mEt1.getText()) && EmailCheckUtils.isNameAdressFormat(mEt1.getText().toString())) {
            mBtnIndentCode.setBackgroundColor(getResources().getColor(R.color.regist_agreement));
            mBtnIndentCode.setClickable(true);
        } else {
            mBtnIndentCode.setBackgroundColor(getResources().getColor(R.color.regist_button));
            mBtnIndentCode.setText(getResources().getString(R.string.regist_get_verification_code));
            mBtnIndentCode.setClickable(false);
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnIndentCode.setBackgroundColor(getResources().getColor(R.color.regist_button));
            mBtnIndentCode.setClickable(false);
            mBtnIndentCode.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            mBtnIndentCode.setText(getResources().getString(R.string.send_again));
            mBtnIndentCode.setClickable(true);
            mBtnIndentCode.setBackgroundColor(getResources().getColor(R.color.regist_agreement));
            mEt1.setFocusableInTouchMode(true);
            mEt1.setFocusable(true);
        }
    }

}
